#set($D="$")   ## Variable for $ sign

CREATE OR REPLACE FUNCTION ${table.logFunctionName}() RETURNS TRIGGER AS ${D}${table.logFunctionName}${D}
DECLARE
   update_type char(1);
   cols text:='';
   values text:='';
   updateAppendsLog boolean = FALSE;
   sync_rest_id uuid;
   trans_id uuid;
   
   BEGIN
   
	#if(${table.updateAppendsLog})
		updateAppendsLog = TRUE;
	#end
   		
   		select get_rest_id() into sync_rest_id;
   		
   		IF (sync_rest_id IS NOT NULL AND (NOT updateAppendsLog)) THEN
   			RETURN NEW;
   		END IF;
   		
		IF (TG_OP = 'INSERT') THEN
			update_type:='I';

		#foreach($col in $table.columns)
			#if($SD_OUTSIDE == $col.syncDirection || $SD_BOTH == $col.syncDirection)
				IF (NEW."${col.name}" IS NOT NULL) THEN
					cols:=cols||'${col.name},';
					#if($col.needsQuotes)
						values:=values||quote_literal(NEW."${col.name}")||',';
					#else
						values:=values||NEW."${col.name}"||',';
					#end
				END IF;
			#end
		#end

		ELSEIF (TG_OP = 'UPDATE') THEN

			update_type:='U';

		#foreach($col in $table.columns)
			#if($SD_OUTSIDE == $col.syncDirection || $SD_BOTH == $col.syncDirection)
				IF (NEW."${col.name}" <> OLD."${col.name}" OR (NEW."${col.name}" IS NULL AND OLD."${col.name}" IS NOT NULL)
				                                   OR (OLD."${col.name}" IS NOT NULL AND NEW."${col.name}" IS NULL)) THEN
					cols:=cols||'${col.name},';
					#if($col.needsQuotes)
						values:=values||quote_literal(NEW."${col.name}")||',';
					#else
						values:=values||NEW."${col.name}"||',';
					#end
				END IF;
			#end
		#end

		END IF;
	
		trans_id = get_trans_id();
		
		INSERT INTO synchronization."${table.logTableName}"(update_type, sync_rest_id, update_time, row_id, cols, values, transaction_id)
		VALUES(update_type, sync_rest_id, clock_timestamp(), NEW."${table.pkColumnName}", cols, values, trans_id);
		RETURN NEW; 

	END;
${D}${table.logFunctionName}$D LANGUAGE plpgsql;
